package com.webshop.servlet;

import com.webshop.Dao.CartDao;
import com.webshop.domain.Cart;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class CartServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method.equals("add")){
            Cart cart = new Cart();
            cart.setId(Integer.parseInt(req.getParameter("product")));
            cart.setNum(Integer.parseInt(req.getParameter("num")));
            HttpSession session = req.getSession();
            List<Cart> carts =(List<Cart>) session.getAttribute("carts");
            if (carts==null){
                carts = new ArrayList<Cart>();
            }
            CartDao.addCart(cart,carts);
            session.setAttribute("carts",carts);
            resp.sendRedirect("cart.jsp");
            return;
        }
        if (method.equals("delete")){
            String id = req.getParameter("id");
            System.out.println(id);
            List<Cart> carts = (List<Cart>)req.getSession().getAttribute("carts");
            Iterator iterator = carts.iterator();
            while (iterator.hasNext()){
                Cart c = (Cart) iterator.next();
                if (String.valueOf(c.getId()).equals(id)){
                    iterator.remove();
                }
            }
            resp.sendRedirect("cart.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
